package com.wbao.dianniu.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.CustomDatePicker;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.PickerView;
import com.wbao.dianniu.customView.PickerView.onSelectListener;
import com.wbao.dianniu.data.ActivityData;
import com.wbao.dianniu.data.ActivityDetailData;
import com.wbao.dianniu.listener.IActivityDetailListener;
import com.wbao.dianniu.listener.ICreateActivityListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.ActivityDetailManager;
import com.wbao.dianniu.manager.CreateActivityManager;
import com.wbao.dianniu.update.ReleaseDataManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 发布活动
 *
 * @author yejianjun
 */
public class CreateActivity extends BaseActivity implements ICreateActivityListener, IActivityDetailListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;
    public static final String RET_DATE = "result_data";
    public static String RET_LAT = "result_lat";
    public static String RET_LONG = "result_long";
    public static String RET_CITY = "result_city";
    public static final String RET_ADDRESS = "result_address";
    public static final int AUTHORITY_REQ_CODE = 911;
    private static final int MAP_REQ_CODE = 999;
    public ActivityData nearData = null;
    private EditText tvSubject;
    private TextView tvPeople;
    private TextView tvTime;
    private EditText etCostMoney;
    private EditText etContent;
    private TextView tvAddress;
    private RelativeLayout relativePeople;
    private RelativeLayout relativeAddress;
    private Button previewBtn;
    private CreateActivityManager manager;
    //弹出选择对话框
    private Dialog dialog;
    private String peopleStr = "";
    private LatLng latLng;
    private Dialog pDialog;
    private CustomDatePicker customDatePicker1;
    private Integer activityId = null;
    private ActivityDetailManager detailManger;
    private String city;
    private final int MAX_COUNT = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_create, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.release_activity));
        initView();
        initData();
        initDatePicker();
        latLng = new LatLng(0, 0);
        if (null != activityId && 0 != activityId) {
            //等待框
            initWattingView();
            waittingLayout.setVisibility(View.VISIBLE);
            detailManger = new ActivityDetailManager(this);
            detailManger.addActDetailListener(this);
            detailManger.reqDetail(GlobalContext.getAccountId(), activityId);
        }
//        Utils.ContentLengthLimit(this, tvSubject, MAX_COUNT);
//        Utils.ContentLengthLimit(this, etCostMoney, 4);
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void initView() {
        tvSubject = findViewById(R.id.activity_subject_text);
        tvPeople = findViewById(R.id.activity_people_text);
        relativePeople = findViewById(R.id.activity_people_rl);
        tvTime = findViewById(R.id.activity_time_text);
        RelativeLayout relativeTime = findViewById(R.id.activity_time_rl);
        relativeAddress = findViewById(R.id.activity_address_rl);
        tvAddress = findViewById(R.id.activity_address_text);
        etCostMoney = findViewById(R.id.activity_CostMoney_edit);
        etContent = findViewById(R.id.activity_content);
        Button btnApply = findViewById(R.id.activity_apply);
        previewBtn = getRightTextButton();
        previewBtn.setText(getResources().getString(R.string.preview));
        previewBtn.setOnClickListener(this);

        relativePeople.setOnClickListener(this);
        relativeTime.setOnClickListener(this);
        relativeAddress.setOnClickListener(this);
        btnApply.setOnClickListener(new NoDoubleClickListener() {

            @Override
            public void onNoDoubleClick(View v) {
                // TODO Auto-generated method stub
                if (checked()) {
                    nearData = new ActivityData();
                    nearData.subject = tvSubject.getText().toString().trim();
                    nearData.maxPersion = Utils.getMaxCounts(tvPeople.getText().toString().trim(), CreateActivity.this);
                    nearData.startDate = tvTime.getText().toString().trim() + ":00";// 时间加上秒
                    nearData.address = tvAddress.getText().toString().trim();
                    nearData.price = Integer.valueOf(etCostMoney.getText().toString().trim());
                    nearData.content = etContent.getText().toString().trim();
                    nearData.longitude = String.valueOf(latLng.longitude);
                    nearData.latitude = String.valueOf(latLng.latitude);
                    submitActivity(nearData);
                }
            }
        });

    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra(Const.BUNDLE_EDIT);
        if (null != bundle) {
            activityId = bundle.getInt(Const.BUNDLE_ID);
            tvSubject.setText(bundle.getString(Const.BUNDLE_SUBJECT, ""));
            tvPeople.setText(bundle.getString(Const.BUNDLE_MAXPERSION, ""));
            tvTime.setText(bundle.getString(Const.BUNDLE_STARTDATE, ""));
            tvAddress.setText(bundle.getString(Const.BUNDLE_ADDRESS, ""));
            etCostMoney.setText(bundle.getString(Const.BUNDLE_PRICE, ""));
            etContent.setText(bundle.getString(Const.BUNDLE_CONTENT, ""));
        }
    }

    private void submitActivity(ActivityData data) {
        pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
        pDialog.show();
        manager = new CreateActivityManager(this);
        manager.addCreateListener(this);
        manager.apply(activityId, GlobalContext.getAccountId(), data.subject,
                data.startDate, data.address, data.maxPersion, data.price,
                data.content, data.longitude, data.latitude, city);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.activity_people_rl:    //活动人数
                // 隐藏键盘
                Utils.hideSoftInput(CreateActivity.this, tvSubject);

                View viewPeoples = showRealase(R.layout.job_release_money);
                PickerView pickerPeople = viewPeoples.findViewById(R.id.picker_money);
                List<String> datasPeople = new ArrayList<String>();
                String[] arrys_peoples = getResources().getStringArray(R.array.activity_peoples_array);
                for (int i = 0; i < arrys_peoples.length; i++) {
                    datasPeople.add(arrys_peoples[i]);
                }
                pickerPeople.setData(datasPeople);
                if ("".equals(peopleStr)) {
                    peopleStr = arrys_peoples[0];
                }
                pickerPeople.setOnSelectListener(new onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        peopleStr = text;
                    }
                });
                Button confirmPeople = viewPeoples.findViewById(R.id.job_money_confirm);
                confirmPeople.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        tvPeople.setText(peopleStr);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.activity_time_rl:    //选择活动开始时间
                // 隐藏键盘
                Utils.hideSoftInput(CreateActivity.this, tvSubject);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                if (TextUtils.isEmpty(tvTime.getText().toString())) {
                    customDatePicker1.show(now);
                } else {
                    customDatePicker1.show(tvTime.getText().toString());
                }
                break;
            case R.id.activity_address_rl:        //活动地点
                Intent mapIntent = new Intent();
                mapIntent.setClass(CreateActivity.this, MapActivity.class);
                mapIntent.putExtra(Const.INTENT_MAP_LAT, latLng.latitude);
                mapIntent.putExtra(Const.INTENT_MAP_LONG, latLng.longitude);
                startActivityForResult(mapIntent, MAP_REQ_CODE);
                break;
            case R.id.right_button:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString(Const.BUNDLE_SUBJECT, tvSubject.getText().toString().trim());
                bundle.putString(Const.BUNDLE_MAXPERSION, tvPeople.getText().toString().trim());
                bundle.putString(Const.BUNDLE_STARTDATE, tvTime.getText().toString().trim());
                bundle.putString(Const.BUNDLE_ADDRESS, tvAddress.getText().toString().trim());
                bundle.putString(Const.BUNDLE_CONTENT, etContent.getText().toString().trim());
                intent.putExtra(Const.BUNDLE_DATA, bundle);
                intent.setClass(CreateActivity.this, ActPreviewActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MAP_REQ_CODE && resultCode == RESULT_OK) {
            if (null != data) {
                double latitude = data.getDoubleExtra(RET_LAT, 0);
                double longitude = data.getDoubleExtra(RET_LONG, 0);
                this.city = data.getStringExtra(RET_CITY);
                latLng = new LatLng(latitude, longitude);
                String address = data.getStringExtra(RET_ADDRESS);
                if (!TextUtils.isEmpty(address)) {
                    tvAddress.setText(address);
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private View showRealase(int layoutId) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();
        }
        View view = LayoutInflater.from(this).inflate(layoutId, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        return view;
    }

    private boolean checked() {
        boolean ret = false;
        if (TextUtils.isEmpty(tvSubject.getText().toString().trim())) {
            toast("输入活动主题");
            tvSubject.requestFocus();
            return ret;
        }
        if (TextUtils.isEmpty(tvPeople.getText().toString().trim())) {
            toast("请选择人数");
            tvPeople.requestFocus();
            return ret;
        }
        if (TextUtils.isEmpty(tvTime.getText().toString().trim())) {
            toast("选择活动开始时间");
            tvTime.requestFocus();
            return ret;
        } else {
            if (Utils.IsActivityStart(tvTime.getText().toString().trim() + ":00")) {
                toast("活动时间必须大于当前时间");
                tvTime.requestFocus();
                return ret;
            }
        }

        if (TextUtils.isEmpty(etCostMoney.getText().toString().trim())) {
            toast("输入金额");
            etCostMoney.requestFocus();
            return ret;
        }
        if (TextUtils.isEmpty(etContent.getText().toString().trim())) {
            toast("内容描述不能为空");
            etContent.requestFocus();
            return ret;
        }
        if (TextUtils.isEmpty(tvAddress.getText().toString().trim())) {
            toast("选择活动地址");
            tvAddress.requestFocus();
            return ret;
        }
        if (!TextUtils.isEmpty(etCostMoney.getText().toString().trim())) {
            int cost = Integer.valueOf(etCostMoney.getText().toString().trim());
            if (cost > 10000) {
                toast("活动金额不能大于10000");
                return ret;
            }
        }
        ret = true;
        return ret;
    }

    private void toast(String msg) {
        Notification.toast(this, msg);
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tvTime.setText(time);
            }
        }, "2017-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 允许循环滚动
    }

    @Override
    public void onActDetailFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
        previewBtn.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onActDetailSuccess(ActivityDetailData objdata) {
        waittingLayout.setVisibility(View.GONE);
        if (null != objdata) {
            display(objdata);
        }
    }

    private void display(ActivityDetailData data) {
        tvSubject.setText(data.info.subject == null ? "" : data.info.subject);
        tvPeople.setText(data.info.maxPersion + "人");
        tvTime.setText(data.info.startDate == null ? "" : data.info.startDate);
        tvAddress.setText(data.info.address == null ? "" : data.info.address);
        etCostMoney.setText(data.info.price + "");
        etContent.setText(data.info.content == null ? "" : data.info.content);
        double longitude = Double.valueOf(data.info.longitude);
        double latitude = Double.valueOf(data.info.latitude);
        latLng = new LatLng(latitude, longitude);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onCreateActivityFailure(int errorCode, String errorMsg) {
//			ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    public void onCreateActivitySuccess() {
        Notification.toast(this, "发布成功");
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 如果是修改活动成功 把修改的数据通知到我发布的界面
        if (null != activityId && 0 != activityId) {
            nearData.id = activityId;
            ReleaseDataManager releaseDataManager = ReleaseDataManager.getInstance();
            releaseDataManager.modifyOneData(activityId, nearData);
        }
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeCreateListener(this);
        }
        if (null != detailManger) {
            detailManger.removeActDetailListener(this);
        }
    }
}
